import query from '@dfeidao/atom-nodejs/db/query';

import { systemid, productid } from '../atom/config';

interface Message {
	filter: {
		[key: string]: string
	};
	page_no: number;
}


interface IGoodsCategory {	// // 商品类别goods_category
	category_num: string;	// 类别编号
	category_name: string;	// 类别名称
	superior_category_number: string;	// 上级类别编号
	level: string;	// 层级
	fzno: string;	// 顺序号
	is_stop: number;	// 是否停用（是1、否0）
	memo: string;	// 备注
}

interface ICommoditySale { 	// 上架商品commodity_sale
	commodity_no: string;	// 商品编号
	commodity_sale_no: string;	// 上架商品编号
	category_num: string;	// 类别编号
	category_name: string;	// 类别名称;
	thumbnail: string;	// 缩略图
}

export default async function atom(msg: Message, action_id: string, session_id: string) {
	const asc = ['fzno'];

	const { exec, prepare } = query(action_id, session_id, systemid);
	const { exec: e2, prepare: p2 } = query(action_id, session_id, systemid);
	const { exec: e3, prepare: p3 } = query(action_id, session_id, systemid);

	prepare('goods_category', ['category_num', 'category_name', 'superior_category_number', 'level'], { ...msg.filter, productid, level: 2 }, 200, 1, asc, []);
	const [goods] = await exec<IGoodsCategory>();


	const category_num_s = goods.map((item) => {
		return item.category_num;
	});
	p2('goods_category', ['category_num', 'category_name', 'superior_category_number'], {
		superior_category_number: {
			$in: category_num_s
		}, productid, level: 3
	}, 200, 1, asc, []);
	const [goods2] = await e2<IGoodsCategory>();

	const l2l = goods2.reduce((p, c) => {
		const category_num = c.superior_category_number;
		const arr = p.get(category_num) as string[];
		if (arr) {
			arr.push(c.category_num);
		} else {
			p.set(category_num, [c.category_num]);
		}
		return p;
	}, new Map());


	const _category_num_s = goods2.map((item) => {
		return item.category_num;
	});
	// return _category_num_s;
	p3('product_information', ['commodity_no', 'category_num', 'category_name', 'commodity_thumbnails'], {
		category_num: {
			$in: _category_num_s
		}, productid
	}, 200, 1, ['create_time'], []);
	const [sale] = await e3<ICommoditySale>();
	// return sale;
	const sale_map = sale.reduce((p, c) => {
		const category_num = c.category_num;
		const arr = p.get(category_num) as ICommoditySale[];
		if (arr) {
			arr.push(c);
		} else {
			p.set(category_num, [c]);
		}
		return p;
	}, new Map());

	const res = goods.reduce((p, c) => {
		const category_num_l2 = c.category_num;
		const category_num_l3 = l2l.get(category_num_l2) as string[];
		const arr = category_num_l3 ? category_num_l3.reduce((_p, i) => {
			const _arr = sale_map.get(i) || [];
			return _p.concat(_arr);
		}, []) : [];
		p.set(category_num_l2, {
			...c, arr
		});
		return p;
	}, new Map());

	return Array.from(res.values());
}
